﻿using System;
using System.Reflection;
using System.ComponentModel;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Net;

namespace Insight.ComClass
{
    //===================================================================
    //ISTString Class
    //===================================================================
    public class InsightString
    {
        public InsightString()
        {
        }

        // 문자열에서 숫자 외의 값을 삭제
        public static string DeleteNonNumber(string AValue)
        {
            string sValue = "";
            for (int i = 0; i < AValue.Length; i++)
            {
                if (((AValue[i] >= '0') && (AValue[i] <= '9')) ||
                    (AValue[i] == '-') || (AValue[i] == '.')) sValue += AValue[i];
            }
            return sValue;
        }

        // 문자열에서 숫자 외의 값을 삭제 (- 제외)
        public static string DeleteNonNumberWithdash(string AValue)
        {
            string sValue = "";
            for (int i = 0; i < AValue.Length; i++)
            {
                if (((AValue[i] >= '0') && (AValue[i] <= '9')) ||
                    (AValue[i] == '.')) sValue += AValue[i];
            }
            return sValue;
        }

        // 문자열에서 숫자인것만 찾기
        public static bool ChkNumber(string AValue)
        {
            bool aReturn = false;

            for (int i = 0; i < AValue.Length; i++)
            {
                if (System.Char.IsNumber(AValue, i))
                    aReturn = true;
                else
                {
                    if (((AValue[i] >= '0') && (AValue[i] <= '9')) || (AValue[i] == '.') || (AValue[i] == ',') || (AValue[i] == '-'))
                        aReturn = true;
                    else
                    {
                        aReturn = false;
                        break;
                    }
                }
            }

            return aReturn;
        }

        // 문자열에서 숫자부분만 떼어서 숫자로 변환
        public static int StrToInt(string AValue)
        {
            int iValue = 0;
            bool bMinus = false;
            AValue = DeleteNonNumber(AValue);
            for (int i = 0; i < AValue.Length; i++)
            {
                if ((AValue[i] >= '0') && (AValue[i] <= '9'))
                    iValue = iValue * 10 + ((int)AValue[i] - (int)'0');
                else if ((i == 0) && (AValue[i] == '-')) bMinus = true;

            }
            if (bMinus) return -iValue;
            else return iValue;
        }

        // 문자열에서 숫자및 '.'문자 떼어서 실수형으로 변환
        public static double StrToFloat(string AValue)
        {
            double dValue = 0;
            int iAfterDot = -1;
            bool bMinus = false;

            AValue = DeleteNonNumber(AValue);
            for (int i = 0; i < AValue.Length; i++)
            {
                if ((AValue[i] >= '0') && (AValue[i] <= '9'))
                {
                    dValue = dValue * 10 + ((int)AValue[i] - (int)'0');
                    if (iAfterDot >= 0) iAfterDot++;
                }
                else if ((i == 0) && (AValue[i] == '-')) bMinus = true;
                else if ((iAfterDot == -1) && (AValue[i] == '.')) iAfterDot = 0;
            }
            for (int i = 0; i < iAfterDot; i++) dValue = dValue / 10;
            if (bMinus) return -dValue;
            else return dValue;
        }

        // 문자형식으로 저장된 boolean값을 읽어옴
        public static bool StrToBool(string AValue)
        {
            return (AValue.Trim().ToUpper() == "TRUE");
        }

        // 숫자를 지정된 길이로 반환, 앞쪽에 '0'을 붙여줌
        public static string IntToStr(int AValue, int ALength)
        {
            string sresult, snumber;
            if (AValue < 0)
            {
                sresult = "-";
                AValue = -AValue;
            }
            else sresult = "";
            snumber = AValue.ToString();
            while ((sresult.Length + snumber.Length) < ALength) sresult += '0';
            sresult += snumber;
            return sresult;
        }

        // Query로 입력하기 위해 앞뒤에 Quote를 붙여줌. 중간 Quote도 처리
        public static string QuotedStr(string AValue)
        {
            string sresult = AValue;
            for (int i = sresult.Length - 1; i >= 0; i--)
                if (sresult[i] == '\'') sresult.Insert(i, "'");
            return ('\'' + sresult + '\'');
        }
        // 문자열 뒤에 공백을 추가하여 붙임...
        public static string GetStrWithSpace(string aValue)
        {
            return aValue + " ";
        }
        // 문자열 뒤에 콤마를 추가하여 붙임...
        public static string GetStrWithComma(string aValue)
        {
            return aValue + ",";
        }

        // 문자를 지정된 길이로 반환, 앞쪽에 빈칸을 붙여줌
        public static string StrFillBlank(string AValue, int ALength)
        {
            string sresult = string.Empty;
            for (int i = AValue.Length; i < ALength; i++)
                sresult += ' ';
            sresult += AValue;
            return sresult;
        }

        //콤마를 붙여줌
        public static string InsertComma(int aValue)
        {
            string aResult = String.Format("{0:###,###,###,###}", aValue);

            if (aResult == "")
                return "0";
            else
                return aResult;
        }

        //콤마를 붙여줌
        public static string InsertCommaDec(decimal aValue)
        {
            string aResult = String.Format("{0:###,###,###,###}", aValue);

            if (aResult == "")
                return "0";
            else
                return aResult;
        }

        //콤마를 떼어낸다
        public static int DeleteComma(string aValue)
        {
            string atmpVal = null;

            for (int i = 0; i < aValue.Length; i++)
            {
                if (aValue[i] != ',')
                    atmpVal = atmpVal + aValue[i];
            }

            if (atmpVal == "")
                return 0;
            else
                return Convert.ToInt32(atmpVal);
        }

        //콤마를 떼어낸다
        public static decimal DeleteCommaDec(string aValue)
        {
            string atmpVal = null;

            for (int i = 0; i < aValue.Length; i++)
            {
                if (aValue[i] != ',')
                    atmpVal = atmpVal + aValue[i];
            }

            if (atmpVal == "")
                return 0;
            else
                return Convert.ToDecimal(atmpVal);
        }

        public static string[] SplitterByComma(string aValue)
        {
            string[] aRval = new string[3];
            char[] aspliter = { ',' };

            if (aValue != "")
            {
                string[] arraySep;
                arraySep = aValue.Split(aspliter);
                for (int i = 0; i < arraySep.Length; i++)
                {
                    aRval[i] = arraySep[i];
                }
            }
            return aRval;
        }

        public static string[] SplitterByChar(string aValue, char aspliter)
        {
            string[] aRval = new string[3];

            if (aValue != "")
            {
                string[] arraySep;
                arraySep = aValue.Split(aspliter);
                for (int i = 0; i < arraySep.Length; i++)
                {
                    aRval[i] = arraySep[i];
                }
            }
            return aRval;
        }

        //Enum 형 데이터를 integer로 변환 string 타입으로 리턴
        public static string ConvEnumToIntStr(object aValue)
        {
            return ((int)aValue).ToString();
        }

        //Enum 형 데이터를 integer로 변환
        public static int ConvEnumToInt(object aValue)
        {
            return ((int)aValue);
        }

        //Enum 형 타입의 설명을 리턴한다.
        public static string GetEnumDesc(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }

        //========================================================================
        // UserId Encription and Decription
        //========================================================================
        public static string EncryptStr(string aValue)
        {
            return Encrypt(aValue, "SmapEX20");
        }
        public static string DecryptStr(string aValue)
        {
            return Decrypt(aValue, "SmapEX20");
        }

        public static string Encrypt(string pToEncrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            //Put the string into a byte array
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);

            //Create the crypto objects, with the key, as passed in
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(),
                CryptoStreamMode.Write);
            //Write the byte array into the crypto stream
            //(It will end up in the memory stream)
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            //Get the data back from the memory stream, and into a string

            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                //Format as hex
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();


        }

        public static string Decrypt(string pToDecrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            //Put the input string into the byte array

            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            //Create the crypto objects
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(),
                CryptoStreamMode.Write);
            //Flush the data through the crypto stream into the memory stream
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            //한글이 decryption 않되는 문제로..Decrypted 된 bytes를 한글로 ecode
            Encoding encode = System.Text.Encoding.GetEncoding("ks_c_5601-1987");
            char[] chars = encode.GetChars(ms.ToArray());
            //Get the decrypted data back from the memory stream
            StringBuilder ret = new StringBuilder();
            ret.Append(chars);
            return ret.ToString();
        }

        //========================================================================
        // DateTime 관련 
        //========================================================================
        // 문자열에서 숫자 외의 값을 삭제
        public static string DateTimeStr(string aValue, string aDateTimeFormat)
        {
            string aReturnValue = "";
            if (aValue.Length >= 10)
            {
                aReturnValue = Convert.ToDateTime(aValue).ToString(aDateTimeFormat);
            }
            return aReturnValue;

        }
        public static string DateTimeStr(DateTime aDateTime, string aDateTimeFormat)
        {
            return aDateTime.ToString(aDateTimeFormat);
        }
        //========================================================================

        public static bool IsDouble(string aString)
        {
            try
            {
                double beTest = Convert.ToDouble(aString);
                return true;
            }
            catch
            {
                return false;
            }

        }


        public static string Copy(string aString, int aStartIndex, int aMaxLength)
        {
            string aReturnValue = "";
            //1. 문자열 길이를 StartIndex가 벗어낫을 경우 공백을 리턴
            if ((aString.Length - aStartIndex) < 1)
                aReturnValue = "";
            //StartIndex가 문자열 내에 포함되면 MaxLength가 그 범위를 벗어날 때
            //StartIndex 부터 문자열 마지막 까지만 리턴한다.
            else if ((aString.Length - aStartIndex - aMaxLength) < 0)
            {
                int aTempMaxLength = aString.Length - aStartIndex;
                aReturnValue = aString.Substring(aStartIndex, aTempMaxLength);
            }
            //StartIndex와 aMaxLength가 문자열 내에 포함될때 정상적인 값을 리턴
            else
                aReturnValue = aString.Substring(aStartIndex, aMaxLength);
            return aReturnValue;

        }

        /// <summary>
        /// DB에 string열에 '을 넣어야 하는 경우
        /// </summary>
        /// <param name="_str">원래 string 열</param>
        /// <returns>string의 [']을 처리한 문자열</returns>
        public static string DBString(string _str)
        {
            string strTemp = string.Empty;
            strTemp = _str.Replace("'", "''");
            return strTemp;
        }

        public static string GetYSRPath()
        {
            string aReturnValue = string.Empty;
            string[] arPath = new string[] { "D:\\YSR2000", "C:\\YSR2000", "E:\\YSR2000", "F:\\YSR2000" };

            try
            {
                for (int Cnt = 0; Cnt < arPath.Length; Cnt++)
                {
                    if (Directory.Exists(arPath[Cnt]))
                    {
                        aReturnValue = MMakePath(arPath[Cnt]);
                        break;
                    }
                }
            }
            finally
            {
            }
            return aReturnValue;
        }

        public static bool IsInternet()
        {
            bool aReturnValue = false;
            string[] arURL = new string[] { "www.naver.com", "www.daum.net" };
            try
            {
                for (int Cnt = 0; Cnt < arURL.Length; Cnt++)
                {
                    IPHostEntry hostInfo = Dns.GetHostByName(arURL[Cnt]);
                    IPAddress[] address = hostInfo.AddressList;
                    if (address[0].ToString() != string.Empty)
                    {
                        aReturnValue = true;
                        break;
                    }
                }
            }
            catch
            {
                aReturnValue = false;
            }

            return aReturnValue;
        }

        public static string MMakePath(string strSrc)
        {
            string aReturnValue = string.Empty;
            int iLen = strSrc.Length;

            if (iLen > 0)
            {
                if (strSrc[iLen - 1] != '\\')
                    aReturnValue = strSrc + "\\";
                else
                    aReturnValue = strSrc;
            }

            return aReturnValue;
        }

        public static string GetISTFilePath()
        {
            string aReturnValue = string.Empty;
            string aYSRPath = GetYSRPath();
            aYSRPath += "ISTFiles";
            try
            {
                if (!Directory.Exists(aYSRPath))
                    Directory.CreateDirectory(aYSRPath);
                aReturnValue = MMakePath(aYSRPath);
            }
            finally
            {
            }

            return aReturnValue;
        }

    }
    //===================================================================
    //===================================================================
    //ISTMath Class
    //===================================================================
    public class ISTMath
    {
        #region [ISTMath]-[con,des]
        public ISTMath()
        {
        }
        #endregion

        #region [ISTMath]-[method]
        //========================================================================
        // method 0:내림, 1:반올림, 2:올림, sosu:얼마까지 표시
        // sosu가 10이면  211 -> 210 0.01이면 0.23->0.20
        //========================================================================
        public static double MRound(double aValue, double aSosu, int aMethod)
        {
            double aReturnValue = 0.0;
            double srcnum = 0.0, znum = 0.0, rnum = 0.0;
            srcnum = aValue / aSosu;
            // 숫자를 0점 대로 끌어내린다.
            znum = Math.Floor(srcnum);
            rnum = srcnum - znum;
            // 내림, 올림, 반올림
            srcnum = znum;
            if (((aMethod == 2) && (rnum != 0.0)) || ((aMethod == 1) && (rnum >= 0.5)))
                srcnum = znum + 1.0;
            if (aSosu > 1) aReturnValue = Math.Round(srcnum * aSosu, 0);
            else aReturnValue = srcnum * aSosu;
            return aReturnValue;
        }
        //========================================================================
        #endregion
    }

    //===================================================================
}
